package com.bnz.servlet;


import com.alibaba.fastjson.JSON;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.bnz.util.PageResult;
import com.bnz.util.R;
import com.bnz.vo.StudentVo;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private StudentService studentService;

    @Override
    public void init() throws ServletException {
        //
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //
        studentService = wac.getBean(StudentService.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //得到请求参数，根据参数调用方法
        String cmd = req.getParameter("cmd");
        if (!StringUtils.isEmpty("cmd")){
            if ("list".equals(cmd)){
                list(req,resp);
            }
        }
    }

    //查询学生
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        //查询所有学生
        List<Student> students = studentService.findAll();
        // 输出到页面
        resp.getWriter().println(JSON.toJSONString(students));
        //刷瓣页面
        resp.getWriter().flush();
    }

    //分页查询
    private void findByPage(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        //得到当前页及每页大小
        String pageStr = req.getParameter("page");
        String pagesizeStr = req.getParameter("pagesize");
        int page = !StringUtils.isEmpty(pageStr) ? new Integer(pageStr) : 1;
        int pagesize = !StringUtils.isEmpty(pagesizeStr) ? new Integer(pagesizeStr) : 5;
        //开始分页
        PageResult<Student> pr = studentService.findByPage(page,pagesize);
        //输出
        resp.getWriter().println(JSON.toJSONString(R.ok().data("pr",pr)));
        //刷瓣页面
        resp.getWriter().flush();
    }

    //条件查询带分页
    private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到当前页及每页大小
        String pageStr = req.getParameter("page");
        String pagesizeStr = req.getParameter("pagesize");
        int page = !StringUtils.isEmpty(pageStr) ? new Integer(pageStr) : 1;
        int pagesize = !StringUtils.isEmpty(pagesizeStr) ? new Integer(pagesizeStr) : 5;
        //得到分页条件对象
        String stud = req.getParameter("stud");
        if(!StringUtils.isEmpty(stud)){
            //转换为中文
            stud = new String(stud.getBytes("iso8859-1"),"UTF-8");
            //再转换为对象
            StudentVo vo = JSON.parseObject(stud,StudentVo.class);
            //开始分页查询
            PageResult<Student> pr = studentService.search(page,pagesize,vo);
            //输出
            resp.getWriter().println(JSON.toJSONString(R.ok().data("pr",pr)));
            //刷瓣页面
            resp.getWriter().flush();
        }
    }

    //添加学生
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String info = "";
        try {
            //得到要添加的学生字符串
            String stud = req.getParameter("stud");
            //转换为中文
            stud = new String(stud.getBytes("iso8859-1"),"UTF-8");
            //转换为学生对象
            Student student = JSON.parseObject(stud,Student.class);
            //添加学生
            studentService.add(student);
            //转换字符串
            info = JSON.toJSONString(R.ok().message("添加学生成功!"));

        } catch (UnsupportedEncodingException e) {
            info = JSON.toJSONString(R.error().message("添加学生失败!"));
            e.printStackTrace();
        }
        //输出
        resp.getWriter().println(info);
        //刷瓣页面
        resp.getWriter().flush();
    }

    //修改学生
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String info = "";
        try {
            //得到要添加的学生字符串
            String stud = req.getParameter("stud");
            //转换为中文
            stud = new String(stud.getBytes("iso8859-1"),"UTF-8");
            //转换为学生对象
            Student student = JSON.parseObject(stud,Student.class);
            //修改学生
            studentService.update(student);
            //转换字符串
            info = JSON.toJSONString(R.ok().message("修改学生成功!"));

        } catch (UnsupportedEncodingException e) {
            info = JSON.toJSONString(R.error().message("修改学生失败!"));
            e.printStackTrace();
        }
        //输出
        resp.getWriter().println(info);
        //刷瓣页面
        resp.getWriter().flush();
    }

    //删除学生
    private void delete(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        String info = "";
        try {
            //得到要删除的学生数组
            String sidstr = req.getParameter("sids");
            //拆分为数组
            String[] sids = sidstr.split(",");
            //将字符串数组转换为List<Integer>集合
            List<Integer> collect = Arrays.stream(sids).map(m -> Integer.parseInt(m)).collect(Collectors.toList());
            //删除学生
            studentService.delete(collect);
            //构造r对象
            info = JSON.toJSONString(R.ok().message("删除学生成功!"));
        } catch (Exception e){
            e.printStackTrace();
            info = JSON.toJSONString(R.error().message("删除学生失败!"));

        }
        System.out.println("info = " + info);
        //输出
        resp.getWriter().println(info);
        //刷瓣页面
        resp.getWriter().flush();
    }
}
